var tmp_evt;
var andy_element;

var TOUCH_START = generateTouchEvent('touchstart');
var TOUCH_END = generateTouchEvent('touchend');
var CLICK = generateHTMLEvent('click');

function dispatchTouchOn(element, eventName){
	var coords = getElementCenter(element);
	var evt = document.createEvent('TouchEvent');
	
	var touches = [];
	var t = document.createTouch(window, element, 12341, coords[0], coords[1], coords[0], coords[1]);
	var t2 = document.createTouch(window, element, 12342, coords[0], coords[1], coords[0], coords[1]);
	touches.push(t);
	touches.push(t2);
	var tl = document.createTouchList(touches);
	
	evt.initTouchEvent(tl, tl, tl, eventName, window, 
				coords[0], coords[1], coords[0],coords[1], 
				false, false, false, false);
	element.dispatchEvent(evt);
}


function generateHTMLEvent(eventName) {
	var evt = document.createEvent('HTMLEvents');
	evt.initEvent(eventName, false, false);
}

function generateMouseEvent(eventName) {
	var evt = document.createEvent('MouseEvents');
	evt.initMouseEvent (eventName, true, true, window, 0, 
				0, 0 ,0 , 0, 
				false, false, false, false, 
				0, null);
	return evt;
}

function generateTouchEvent(eventName) {
	var evt = document.createEvent('TouchEvent');
	evt.initTouchEvent(null, null, null, eventName, window, 
				0, 0, 0, 0, 
				false, false, false, false);
	return evt;
}





function getText(element) {
	if (element == null)
		return null;
	
	if (element.textContent)
		return element.textContent;
	else if (element.innerText)
		return element.innerText;
	else
		return null;
}

function getClassName(elem) {
	if (! elem) return null;
	if (elem.className) return elem.className;
	else if (elem.getAttribute) return elem.getAttribute("class");
	return null;
}

function getElementCSSValue (element, attr) {
	try{
		if(element.currentStyle)
			return element.currentStyle[attr];
		else
			return document.defaultView.getComputedStyle(element, false).getPropertyValue(attr);
	}
	catch(e){
		return null;
	}
}






function getElementByText(text){
	var nodes = document.getElementsByTagName('*');
	var node;

	for (var i = 0; i < nodes.length; i++) {
		node = nodes[i];
		var nodeInnerText = getText(node) ? getText(node).format() : null;
		if (nodeInnerText && nodeInnerText == text){
			return node;
		}
	}
	return null;
}

function getElementByTagAndText(tag, text, isInclude){
	var nodes = document.getElementsByTagName(tag);
	var node;

	for (var i = 0; i < nodes.length; i++) {
		node = nodes[i];
		var nodeInnerText = getText(node) ? getText(node).format() : null;
		if (nodeInnerText) {
			if (isInclude == 'true'){
				if (nodeInnerText.indexOf(text) != -1)
					return node;
			}
			else{
				if (nodeInnerText == text)
					return node;
			}
		}
	}
	return null;
}

function getElementByXPath(xpath) {
	var result = parseOrdinal(xpath);
	var ordinal = Number(result.ordinal);
	var content, tagName; 
	if (!isNaN(ordinal)) {
		content = result.content;
		result = parseTagAndAttr(content);
		tagName = result.content;
		content = result.attr;
	} 
	else {
		ordinal = 0;
		result = parseTagAndAttr(xpath);
		tagName = result.content;
		content = result.attr;
	}
	
	var conditions = content.split(" and ");
	var names = [];
	var values = [];
	var functions = [];
	for (var i = 0; i < conditions.length; i++){
		var cond = conditions[i];
		var at, equals, comma, name, value;
		if (cond.indexOf('contains')>=0) {
			at = cond.indexOf("@");
			comma = cond.indexOf(",");
			if (at<0 || comma<0)
				return null;
			name = cond.substring(at+1, comma).trim();
			value = cond.substring(comma+1, cond.length);
			functions.push("contains");
		}
		else if (cond.indexOf('=')>=0){
			at = cond.indexOf("@");
			equals = cond.indexOf("=");
			if (at<0 || equals<0)
				return null;
			name = cond.substring(at+1, equals).trim();
			value = cond.substring(equals+1, cond.length);
			functions.push("=");
		}
		values.push(value.substring(value.indexOf("\'")+1, value.lastIndexOf("\'")).trim());
		names.push(name);
	}
	var nodes = document.getElementsByTagName(tagName);
	var count = 0;
	for (var i = 0; i < nodes.length; i++) {
		var element = nodes[i];
		var conditionSatisfied = true;
		for (var j = 0; j < names.length; j++){
			var attrValue;
			if (names[j] == "class")	attrValue = getClassName(element);
			else if (names[j] == "text")	attrValue = getText(element);
			else	attrValue = element.getAttribute(names[j]);
			if (attrValue == null) {
				conditionSatisfied = false;
				break;
			}
			else
				attrValue = attrValue.trim();
			
			if (functions[j] == "=") {
				if (values[j] != attrValue) {
					conditionSatisfied = false;
					break;
				}
			}
			else if (functions[j] == "contains") {
				if (attrValue.indexOf(values[j]) < 0) {
					conditionSatisfied = false;
					break;
				}
			}
		}
		if (conditionSatisfied == true) {
			if (count++ == ordinal)
				return element;
		}
	}
	return null;
}

function getElementByTagAndCondition(tag, condition){
	var nodes = document.getElementsByTagName(tag);
	var node;

	for (var i = 0; i < nodes.length; i++) {
		node = nodes[i];
		if (eval(condition)) {
			return node;
		}
	}
	return null;
}

function parseOrdinal(text) {
	var leftPos = text.lastIndexOf("[");
	var rightPos = text.lastIndexOf("]");
	var content = text;
	var ordinal = 0;
	if (leftPos >= 0 && rightPos >= 0 && leftPos < rightPos) {
		ordinal = text.substring(leftPos+1, rightPos);
		content = text.substring(0, leftPos);
	}
	var retval = {content: content, ordinal: ordinal};
	return retval;
}

function parseTagAndAttr(text) {
	var leftPos = text.indexOf("[");
	var rightPos = text.lastIndexOf("]");
	var content = text;
	var attr = null;
	if (leftPos >= 0 && rightPos >= 0 && leftPos < rightPos) {
		attr = text.substring(leftPos+1, rightPos);
		content = text.substring(0, leftPos);
	}
	var retval = {content: content, attr: attr};
	return retval;
}





function getElementCenter(element) {
    var width =  element.clientWidth;
    var height = element.clientHeight;
    var result = [element.offsetLeft, element.offsetTop];
    element = element.offsetParent;
    while (element) {
        result[0] += element.offsetLeft;
        result[1] += element.offsetTop;
        element = element.offsetParent;
    }
    return [result[0]+width/2, result[1]+height/2];
}

function getElementPosition(element) {
    var width =  element.clientWidth;
    var height = element.clientHeight;
    var result = [element.offsetLeft, element.offsetTop];
    element = element.parentNode;
    var flag = false;
    while (element) {
    	var webkit_transform_str = getElementCSSValue(element, '-webkit-transform');
    	
    	if (webkit_transform_str && webkit_transform_str != 'none'){
    		try {
	    		var pos_left_brace = webkit_transform_str.indexOf('(');
	    		var pos_right_brace = webkit_transform_str.indexOf(')');
	    		var matrix_str = webkit_transform_str.substring(pos_left_brace+1, pos_right_brace);
	    		var matrix_cells = matrix_str.split(',');
	    		var matrix = [];
	    		for (var i in matrix_cells) {
	    			matrix.push(parseFloat(matrix_cells[i].trim().replace('px', '')));
	    		}	    		
	    		result[0] = matrix[0] * result[0] + matrix[1] * result[1] + matrix[4];
	    		result[1] = matrix[2] * result[0] + matrix[3] * result[1] + matrix[5];
    		}
    		catch(e){
    			alert('error: ' + matrix_str);
    		}
    	}
    	if (element.offsetLeft != null && element.offsetTop != null) {
	        result[0] += element.offsetLeft;
	        result[1] += element.offsetTop;
    	}
        element = element.parentNode;
    }
    
    return result[0]+','+result[1]+','+width+','+height;
}



function isElementPresent(){
	if (andy_element)	return true;
	else return false;
}



function displayProperties(obj){
	var str = '--- '+typeof(obj) +' | '+obj + ' ---\n';
	var count = 0;
	for (var i in obj)
		str += '('+(++count)+'): '+ i +' | '+typeof(i)+' | '+obj[i] + '\n';
	alert(str);
}

function initHTMLViewer(){	
	window.addEventListener('touchmove', function(ev){
		alert(ev.target.outerHTML);	
	}, false)
}

function initDebugger(){	
	window.addEventListener('touchmove', function(ev){
		alert(getDocumentData());
	}, false)
}

function init(){
}

init();

String.prototype.format = function(){
	var s = this;
	s = s.replace(/\u00a0/g, " ");
	return s;
}
